package com.google.code.lightsomy.output;

import java.io.StringWriter;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;

import com.google.code.lightsomy.errors.ApplicationException;
import com.google.code.lightsomy.http.LightsomyConstants;

/**
 * Renderer implementation for Velocity template engine.
 * 
 * @author Viktoras Agejevas
 *
 */
public class VelocityRenderer extends LightsomyRenderer {

	final private VelocityContext context;

	
	VelocityRenderer(HttpServletRequest req, HttpServletResponse res) {
		super(req, res, Type.VELOCITY);
		
		String path = req.getSession().getServletContext().getRealPath("/");
		Properties props = new Properties();
	    props.put("resource.loader", "file");
	    props.put("file.resource.loader.path", path);
	    props.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, 
	    		"org.apache.velocity.runtime.log.Log4JLogChute");
	    props.put("runtime.log.logsystem.log4j.logger", "org.apache.velocity");

	    try {
			Velocity.init(props);
		} catch (Exception e) {
			throw new ApplicationException("Failed to init Velocity", e);
		}
		
        context = new VelocityContext();
        set("root", 
        		req.getParameter(
        				LightsomyConstants.LIGHTSOMY_ROOT_URL.getValue()));
        set("resources", 
        		req.getParameter(
        				LightsomyConstants.LIGHTSOMY_RESOURCES_ROOT_URL.getValue()));
	}
	
	@Override
	public Object get(String key) {
		return context.get(key);
	}

	@Override
	public void set(String key, Object value) {
		context.put(key, value);
	}

	@Override
	protected String process(String page) {
        StringWriter w = new StringWriter();
        
        try {
			Velocity.mergeTemplate(page, "UTF-8", context, w);
		} catch (Exception e) {
			throw new ApplicationException("Failed to render the template", e);
		}
        
		return w.toString();
	}

}
